package com.example.ecommercemarketing.handler.impl;

import com.example.common.Util;
import com.example.ecommercemarketing.dto.MarketingElementsDTO;
import com.example.ecommercemarketing.dto.ProductDTO;
import com.example.ecommercemarketing.dto.UserDTO;
import com.example.ecommercemarketing.handler.MarketingElementsHandler;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 通过地区热销获取营销素材
 */
public class RegionalPopularHandler implements MarketingElementsHandler {

    @Override
    public MarketingElementsDTO handle(ProductDTO product, UserDTO user) {
        // 获取用户地区
        String userRegion = getUserRegion(user);
        if (Util.isNullOrEmpty(userRegion)){
            return null;
        }

        // 检查商品是否在该地区热销
        if (!userRegion.equals(product.getRegion())) {
            return null;
        }

        //这里直接写死了一些测试数据，实际项目中是通过发其它应用的接口、查数据库、经过一些繁琐的业务逻辑处理来获取数据的
        MarketingElementsDTO elements = new MarketingElementsDTO();
        elements.setRecommendText("【" + userRegion + "热销】" + product.getName() + "，" + userRegion + "用户最爱！");
        elements.setProductHighlights("本地热销，深受" + userRegion + "用户喜爱");
        elements.setMarketingImageUrl("https://example.com/marketing/regional/" + product.getId() + ".jpg");
        elements.setExtraInfo(userRegion + "地区热销商品");
        elements.setSource("regional_popular");

        Random random = new Random();
        int randomTime = random.nextInt(15);
        //模拟实际业务中的耗时
        try {
            TimeUnit.MILLISECONDS.sleep(randomTime);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        return elements;
    }

    private String getUserRegion(UserDTO user) {
        // 优先使用手机定位，其次使用常用收货地址
        if (!Util.isNullOrEmpty(user.getLocation())) {
            return user.getLocation();
        }
        if (!Util.isNullOrEmpty(user.getCommonAddress())) {
            return user.getCommonAddress();
        }
        return null;
    }
}